﻿using DongFangGuoKai.WCSPlatform.WebApi.Utils;
using S7.Net;

namespace DongFangGuoKai.WCSPlatform.WebApi.HostService
{
    /// <summary>
    /// 入库后台任务
    /// </summary>
    public class InWhouseHostService : BackgroundService
    {
        private readonly PlcTaskManager plcTaskManager;
        private readonly Plc plc;
        private readonly ILogger<InWhouseHostService> logger;
        /// <summary>
        /// 构造
        /// </summary>
        /// <param name="plcTaskManager"></param>
        /// <param name="plc"></param>
        /// <param name="logger"></param>
        public InWhouseHostService(PlcTaskManager plcTaskManager,Plc plc,ILogger<InWhouseHostService> logger)
        {
            this.plcTaskManager = plcTaskManager;
            this.plc = plc;
            this.logger = logger;
        }
        
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                logger.LogInformation("入库任务启动");
                while (true)
                {
                    try
                    {
                        if (plc.IsConnected)
                        {
                            plcTaskManager.InDoWork();
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.LogError($"入库任务异常:{ex.Message}");
                    }

                    await Task.Delay(1000);
                }
            }
            catch (Exception ex)
            {
                logger.LogError($"入库任务异常:{ex.Message}");
                StopAsync(stoppingToken);
            }
        }
        public override Task StopAsync(CancellationToken cancellationToken)
        {
            Dispose();
            logger.LogInformation("入库后台任务异常结束");
            return base.StopAsync(cancellationToken);
        }
    }
}
